import { useIntersectionObserver, useIntervalFn } from "@vueuse/core";
import { onMounted, ref } from "vue";

export function useLazyData(fn: () => void) {
  const target = ref(null);
  onMounted(() => {
    const { stop } = useIntersectionObserver(
      target.value,
      ([{ isIntersecting }]) => {
        //  可见
        if (isIntersecting) {
          // 发请求
          fn()
          // 停止监听
          stop();
        }
      }
    );
  });
  return target
}

export function useCountDown() {
  const counter = ref(0)
  const { pause, resume } = useIntervalFn(() => {
    if (counter.value === 0) {
      pause()
    } else {
      counter.value--
    }
  }, 1000, { immediate: false })
  const start = (num: number) => {
    counter.value = num
    resume()
  }

  return { counter, start }
}